<template>
	<view v-if="showPage" class="">
		<block v-for="item in list" :key="item.id">
			<view class="z-card fd-r p-24" @click="HGoBack(item)">
				<view class="flex1 fd-c fs-28">
					<text>{{ item.realName }} {{ item.phone }}</text>
					<text class="mt-12">
						{{ item.province }}{{ item.city }}{{ item.area
						}}{{ item.address }}
					</text>
					
					<text v-if="item.isDefault" class="c-red">默认地址</text>
				</view>
				<view class="p-12" @click.stop="HEdit(item)">
					<tm-icon name="tmicon-edit" color="primary"></tm-icon>
				</view>
				<view class="p-12" @click.stop="HDel(item)">
					<tm-icon name="tmicon-delete-fill" color="red"></tm-icon>
				</view>
			</view>
		</block>

		<tm-result
			v-if="list.length == 0"
			title="空空如也~"
			subTitle="去新建一个吧"
			:showBtn="false"
		></tm-result>
		<view class="px-24 pt-24">
			<button class="btn-red" @click="HGotoAdd">新增地址</button>
		</view>
	</view>

	<tm-skeleton v-else></tm-skeleton>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const showPage = ref(false);

import addressApi from '@/api/addressApi.js';
const list = ref([]);
const hidePartOfPhoneNumber = (phoneNumber, start, length) => {
	// 构造一个正则表达式，用于匹配并替换指定的位置和长度的字符
	const regex = new RegExp(`(\\d{${start}})(\\d{${length}})(\\d+)`);
	return phoneNumber.replace(regex, `$1${'*'.repeat(length)}$3`);
};
const HGetList = () => {
	// 获取地址列表
	addressApi.page().then((res) => {
		list.value = res.data.records.map((v) => {
			v.phone = hidePartOfPhoneNumber(v.phone, 3, 4);
			return v;
		});
		showPage.value = true;
	});
};

let isSelect;
onLoad((options) => {
	isSelect = !!options.select;
	HGetList();
});

const HGotoAdd = () => {
	uni.navigateTo({
		url: '/pages/zone1/address/add/index'
	});
	uni.$once('address-add-back', () => {
		HGetList();
	});
};

const HGoBack = (item) => {
	if (isSelect) {
		uni.$emit('address-back', item);
		uni.navigateBack();
	}
};

const HEdit = (item) => {
	uni.navigateTo({
		url: '/pages/zone1/address/add/index',
		success: (res) => {
			res.eventChannel.emit('address-edit', item);
		}
	});

	uni.$once('address-add-back', () => {
		HGetList();
	});
};

const HDel = (item) => {
	uni.showModal({
		title: '提示',
		content: '确定删除该地址吗？',
		success: (res) => {
			if (res.confirm) {
				addressApi.del(item.id).then(() => {
					HGetList();
				});
			}
		}
	});
};
</script>

<style></style>
